package com.shiwaixiangcun.customer.module.heath

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.ui.fragment.LazyFragment
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.tencent.smtt.sdk.*
import kotlinx.android.synthetic.main.layout_fragment_plan.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author   Administrator
 * Date     2018/1/22
 * Desc     健康方案
 * @author Administrator
 */

class FragmentPlan : LazyFragment() {

    companion object {

        val BUG_TAG = "fragmentPlan"
        val CHANGE_TAB = 0x1010
        fun newInstance(userID: Long?): FragmentPlan {
            val f = FragmentPlan()
            val args = Bundle()
            args.putLong("userID", userID!!)
            f.arguments = args
            return f

        }
    }

    private var url: String? = null
    private var strToken: String? = null
    private var userID: Long? = null
    override fun getContentViewLayoutID(): Int {
        return R.layout.layout_fragment_plan
    }

    override fun initViewsAndEvents(view: View) {


        strToken = AppSharePreferenceMgr.get(activity, ConfigSps.CURRENT_TOKEN, "") as String
        url = "${GlobalApi.healthPlan}?access_token=$strToken&customerId=$userID"
        webView.clearCache(true)

        webView.webChromeClient = MyWebChromeViewClient()
        webView.webViewClient = MyWebViewClient()
//        webView.loadUrl(url)
    }

    /**
     * 清除Cookie
     *
     * @param context
     */
    private fun removeCookie(context: Context) {
        CookieSyncManager.createInstance(context)
        val cookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        CookieSyncManager.getInstance().sync()
    }




    override fun onFirstUserVisible() {
        if (userID == 0L) {
            return
        }

        webView.loadUrl(url)
        Log.e(BUG_TAG, "${webView.left}")
    }

    override fun onUserVisible() {
        webView.loadUrl(url)
    }

    /**
     * 请求数据
     */
    private fun initUrl(id: Long?) {

        url = "${GlobalApi.healthPlan}?access_token=$strToken&customerId=$id"

    }

    override fun onUserInvisible() {

    }

    override fun destroyViewAndThing() {

        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webView.clearHistory()

            (webView.parent as ViewGroup).removeView(webView)
            webView.destroy()
        }
        EventUtil.getInstance().unregister(this)

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bundle = arguments
        if (bundle != null) {
            userID = bundle.getLong("userID")
        }
        EventUtil.getInstance().register(this)
    }


    /**
     * EventBus
     *
     * 数据更新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        when (simpleEvent.mEventType) {
        //当切换家人的时候执行
            SimpleEvent.HEALTH_CHANGE_FAMILY -> {
                when (simpleEvent.mEventValue) {
                    CHANGE_TAB -> {
                        val changeID = simpleEvent.data as Long
                        userID = changeID
                        initUrl(userID)
                        if (isUserVisiable) {
                            Log.e(BUG_TAG, "切换ID为 $userID")

                            webView.loadUrl(url)
                        }

                    }
                }
            }

            else -> {
                return
            }
        }

    }


    private inner class MyWebChromeViewClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                progressBar.visibility = View.GONE
            } else {
                if (View.INVISIBLE == progressBar.visibility) {
                    progressBar.visibility = View.VISIBLE
                }
                progressBar.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }


    }

    /**
     * 处理通知 ，请求事件
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }
    }

}
